{% extends 'base/base_site.html' %}
{% block css %}
    {{ block.super }}
{% endblock %}
{% block content %}
    <div class="ibox-title" style="background-color:#FFFFCE">
        <h5>{{ idcName }}</h5>
    </div>
    <div class="ibox-content">
        <div id="DataTables_Table_0_wrapper" class="dataTables_wrapper form-inline">
            <div class="row">
                <div class="col-sm-8">
                    <div class="dataTables_length" id="DataTables_Table_0_length" style="margin-bottom:15px;">
                        {{ request.perms.List }}
{#                        <a class="btn btn-sm btn-success btn-add" data-toggle="modal" data-target="#addInfoModal"><i#}
{#                                class="fa fa-plus"></i> 添加主机</a>#}
                        <input type="text" placeholder="搜索: 服务、名称、IP等" id="search" class="form-control input-sm">
                    </div>
                </div>
            </div>
            <table class="table table-striped table-bordered table-hover dataTables-example dataTable dtr-inline"
                   id="DataTables_Table_0" role="grid" aria-describedby="DataTables_Table_0_info">
                <thead>
                <tr role="row">
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1" aria-sort="ascending">序号
                    </th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">IP</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">项目名称</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">服务名称</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">运行状态</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">创建时间</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">操作</th>

                </tr>
                </thead>
                <tbody id="content">
                {% include 'cmdb/idc_server_table.html' %}
                </tbody>
            </table>

            {% include 'common/paginator.html' %}
        </div>
    </div>
    {% include 'cmdb/idc_server_modal.html' %}
{% endblock %}
{% block javascripts %}
    {{ block.super }}
{#    <script src="/static/js/plugins/chosen/chosen.jquery.js" type="text/javascript"></script>#}
{#    <script src="/static/js/plugins/iCheck/icheck.min.js"></script>#}


    <script type="text/javascript">
        function resetChosen() {
            var config = {
                '.chosen-select': {
                    width: "100%"
                },
                '.chosen-select-deselect': {
                    allow_single_deselect: true
                },
                '.chosen-select-no-single': {
                    disable_search_threshold: 10
                },
                '.chosen-select-no-results': {
                    no_results_text: 'Oops, nothing found!'
                },
                '.chosen-select-width': {
                    width: "100%"
                },

            }
            for (var selector in config) {
                $(selector).chosen(config[selector]);
            }
            $('#groups').trigger("chosen:updated");
            $('#edit_groups').trigger("chosen:updated");
        }

        Array.prototype.contains = function (needle) {
            for (i in this) {
                if (this[i] == needle) return true;
            }
            return false;
        }
    </script>

    <script type="text/javascript">

        $('.btn-add').on('click', function () {

            var groups = {{groups |safe}};
            reset();
            $('#groups').empty();
            $.each(groups, function (key, value) {
                var obj = document.getElementById("groups");
                var op = new Option(value[1], value[0])
                obj.add(op);
            });
            resetChosen();
        });

        /**
         * 编辑表单
         * **/

        $('.btn-edit').on('click', function (event) {

            var groups = {{ groups | safe}};
            var idcs ={{ idcs | safe}};
            var apps = {{ apps | safe }};


            var btn = $(event.target);
            var row = btn.data('row').split('|');

            $('#server_id').val(row[0]);
{#            $('#project_name').val(row[1]);#}
{#            $('#service_name').val(row[2]);#}
            $('#in_ip').val(row[3]);
            $('#ex_ip').val(row[4]);

            $('#edit_idc').empty();
            $('#edit_groups').empty();
            $('#edit_app').empty();

            var idc = row[6];
            var app = row[7];
            $('#edit_idc').append("<option value=''>----------</option>");
            jQuery.each(idcs,function (key, value) {
                var t = jQuery("<option value=" + value[0]+">" + value[1] + "</option>");
               if(value[0] == idc){
                    t.attr("selected","selected");
               }
                $('#edit_idc').append(t);
            });

            $('#edit_app').append("<option value=''>----------</option>");
            jQuery.each(apps, function (key, value) {
                var t = jQuery("<option value=" + value[0] + ">" + value[1] + "（" + value[2] + "）" + "</option>");
                if (value[0] == app) {
                    t.attr("selected", "selected");
                }
                $('#edit_app').append(t);
            });


            row_group = row[5].split(',');
            if (groups != "") {
                $.each(groups, function (key, value) {
                    var obj = document.getElementById("edit_groups");
                    var op = new Option(value[1], value[0])
                    if (row_group.contains(value[1])) {
                        op.selected = true;
                    }
                    obj.add(op);
                });
            } else if (groups == "") {

                $.each(groups, function (key, value) {
                    var obj = document.getElementById("edit_groups");
                    var op = new Option(value[1], value[0])
                    obj.add(op);
                });
            }
            resetChosen();
        })
    </script>

    <script>
        /*
*更新机器信息
*/
        $("table tbody tr td a[id^='server_update']").click(function () {
            var id_val = $(this).attr('id'); //获取更新按钮id值
            var id = id_val.split('_')[2]; //获取id值的最后一位
            var data = {"id": id};
            data = JSON.stringify(data);
            var url = "/cmdb/postmachineinfo/";

            $.get(url, {data: data}, function (msg) {
                update_ajax_callback(msg, {{ idcId }});
            });
        });


        /*
        *删除机器信息
        */
        $("table tbody tr td a[id^='server_delete']").click(function () {
            var id_val = $(this).attr('id');
            var id = id_val.split('_')[2];
            var data = {"id": id};
            data = JSON.stringify(data);
            var url = "/cmdb/server_delete/";

            var index = layer.confirm('确定删除吗？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.post(url, {data: data}, function (msg) {
                    update_ajax_callback(msg, {{ idcId }});
                });
            }, function () {
                layer.close(index)
            });
        });


        /*
        *保存编辑服务器信息数据
        */
        $('#editSave').click(function () {
            var server_id = $("#server_id").val();
            var in_ip = $("#in_ip").val();
            var ex_ip = $("#ex_ip").val();
{#            var project_name = $("#project_name").val();#}
{#            var service_name = $("#service_name").val();#}
            var groups = $("#edit_groups").val();
            var idc = $("#edit_idc").find("option:selected").val();
            var app = $("#edit_app").find("option:selected").val();
            data = {
{#                "project_name": project_name,#}
{#                "service_name": service_name,#}
                "in_ip": in_ip,
                "ex_ip": ex_ip,
                "groups": groups,
                "idc": idc,
                "app": app,
                "id": server_id
            };
            data = JSON.stringify(data);
            var url = "/cmdb/server_edit/";

            $.post(url, {data: data}, function (msg) {
                $('#editInfoModal').modal('hide')
                update_ajax_callback(msg, {{ idcId }});
            });
        });

        /*
*ajax get callback
*/
        function update_ajax_callback(msg, id) {
            var msg = $.parseJSON(msg);
            var index = layer.alert(msg, { //layer控件提示信息
                skin: 'layui-layer-molv' //样式类名
            }, function () {
                if (msg == '成功') {
                    window.location = "/cmdb/idc_server_detail/" + id;
                }
                else if (msg == '失败') {
                    window.location = "/cmdb/idc_server_detail/" + id;
                }
                    {#        else if (msg == '无权限操作'){#}
                    {#            window.location="/cmdb/server_list/";#}
                    {#        }#}
                else {
                    layer.close(index)
                }
            });
        }


    </script>
    <!-- 实时搜索 -->
    <script type="text/javascript">
        var flag;

        function func1() {
            clearTimeout(flag);
            flag = setTimeout(function () {
                data();
            }, 200);

        }

        function data() {
            search = $('#search').val();
            $.ajax({
                url: '{% url 'idc_server_search' %}',
                type: 'GET',
                dataType: 'html',
                data: {"search": search, "idcId": {{ idcId }}},
                success: function (data) {
                    $("#content").html(data);
                }
            });
        }

        $("#search").keyup(function (event) {
            func1();
        });
    </script>
    <!-- 实时搜索End -->


    <script type="text/javascript">
        function reset() {
            $('#email').val("");
        }

        String.prototype.bool = function () {
            return (/^true$/i).test(this);
        };
    </script>

    <script type="text/javascript">

        $('.btn-email').on('click', function (event) {
            var btn = $(event.target);
            var row = btn.data('row').split('|');
            var id = row[0];
            var cauthor = row[1];
            var nuser = "{{ request.session.fullname }}";
            if (cauthor == nuser || "{{ request.user.is_superuser }}".bool()) {
                $("a").attr("data-target", "#editor");
                $("#email").empty();
                $.get("{% url 'get_email' %}", function (data, status) {
                    if (data.length > 0 && status == "success") {
                        $.each(jQuery.parseJSON(data), function (k, v) {
                            var obj = document.getElementById("email");
                            var op = new Option(v.name, v.name)
                            obj.add(op);
                        })
                    }
                    resetChosen();

                });

                $('.btn-commit').on('click', function () {
                    var email_group = $('#email').val();
                    $.ajax({
                        type: "POST",
                        url: "{% url 'send_mails' %}",
                        async: true,
                        data: {"content_id": id, "email_group": JSON.stringify(email_group)},
                        success: function (data, textStatus) {
                            window.location.reload()
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest.status);
                            alert(XMLHttpRequest.readyState);
                            alert(textStatus);
                        },
                    });
                });
            }
            else {
                $("a").removeAttr("data-target");
                alert("只有创建者才可以发送通知！");
            }

        });

    </script>

{% endblock %}